//
//  WBWelcomeView.swift
//  WB
//
//  Created by macssss on 16/7/6.
//  Copyright © 2016年 macssss. All rights reserved.
//

import UIKit
import SDWebImage

class WBWelcomeView: UIView {
    //头像视图
    @IBOutlet weak var iconView: UIImageView!
    //欢迎文字
    @IBOutlet weak var welcomeLabel: UILabel!
    //图像距离底部的高度
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    
    @IBOutlet weak var iconWidthCons: NSLayoutConstraint!
    
    class func welcomeView()-> WBWelcomeView {
        
        let nib = UINib.init(nibName: "WBWelcomeView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView

        v.frame = UIScreen.main().bounds

        return v
    }
  
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        
        // 提示：initWithCode 只是刚刚从 XIB 的二进制文件将视图数据加载完成
        // 还没有和代码连线建立起关系，所以开发时，千万不要在这个方法中处理 UI
        print("initWithCoder + \(iconView)")

    
    }
    
    
    override func awakeFromNib() {
        
        guard let urlString = WBNetworkManager.shared.userAccount.avatar_large,
         let url = URL(string: urlString) else {
            return
        }
        
        iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
        
        iconView.layer.cornerRadius = iconWidthCons.constant * 0.5
        iconView.layer.masksToBounds = true
        
    }
    
    override func didMoveToWindow() {
      super.didMoveToWindow()

        // 视图是使用自动布局来设置的，只是设置了约束
        // - 当视图被添加到窗口上时，根据父视图的大小，计算约束值，更新控件位置
        // - layoutIfNeeded 会直接按照当前的约束直接更新控件位置
        // - 执行之后，控件所在位置，就是 XIB 中布局的位置
        //FIXME: XIB自动布局欢迎动画很关键
        self.layoutIfNeeded()
        
        bottomCons.constant = bounds.size.height - 200
        
        //动画效果
        UIView.animate(withDuration: 2.0,
                       delay: 0,
                       usingSpringWithDamping: 0.7,
                       initialSpringVelocity: 0,
                       options: [],
                       animations: {
                        //更新约束
                        self.layoutIfNeeded()
                        
            }) { (_) in
               
                UIView.animate(withDuration: 1.0, animations: { 
                    
                    self.welcomeLabel.alpha = 1
                    
                    }, completion: { (_) in
                        
                        //从父视图删除自己
                        self.removeFromSuperview()
                })
                
        }
        
    }

}
